package com.yuexia.sell.service.impl;

import com.yuexia.sell.converter.OrderMasterToOrdeDtoConverter;
import com.yuexia.sell.dao.OrderMasterDao;
import com.yuexia.sell.dao.ProductInfoDao;
import com.yuexia.sell.dao.OrderDetailDao;
import com.yuexia.sell.dataOjbect.OrderDetail;
import com.yuexia.sell.dataOjbect.OrderMaster;
import com.yuexia.sell.dataOjbect.ProductInfo;
import com.yuexia.sell.dto.CartDTO;
import com.yuexia.sell.dto.OrderDTO;
import com.yuexia.sell.enums.OrderStatusEnum;
import com.yuexia.sell.enums.PayStatusEnum;
import com.yuexia.sell.enums.ResultEnum;
import com.yuexia.sell.exception.SellException;
import com.yuexia.sell.service.Interface.OrderService;
import com.yuexia.sell.service.Interface.ProductInfoService;
import com.yuexia.sell.util.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单管理接口实现类
 * @author itmrchen
 * @date 2018/7/11 0011 下午 2:50
 * @desc ctrate by YUE XIA
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMasterDao orderMasterDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private ProductInfoService productInfoService;

    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {

        String ORDERID = KeyUtil.genUniqueKey();
        BigDecimal ORDERAMOUNT = new BigDecimal(BigInteger.ZERO);

        //1.查询 库存 价格
        for (OrderDetail orderDetail :orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = productInfoDao.findOne(orderDetail.getProductId());
            if(productInfo == null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            //2.计算总价
            ORDERAMOUNT = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(ORDERAMOUNT);

            //3.1订单详情存入数据库
            BeanUtils.copyProperties(productInfo,orderDetail);
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(ORDERID);
            orderDetailDao.save(orderDetail);
        }
        //3.2写入订单数据库
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderDTO.setOrderId(ORDERID);
        orderMaster.setOrderAmount(ORDERAMOUNT);
        orderMaster.setOrderId(ORDERID);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());

        orderMasterDao.save(orderMaster);

        //4.减库存
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e ->
                new CartDTO(e.getProductId(), e.getProductQuantity())
        ).collect(Collectors.toList());

        orderDTO.getOrderDetailList();

        productInfoService.decreaseStock(cartDTOList);

        return orderDTO;
    }

    //    查询单个订单
    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster orderMaster = orderMasterDao.findOne(orderId);
        if (orderMaster == null){
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = orderDetailDao.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)){
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }

    //    查询订单列表        根据openid
    @Override
    public Page<OrderDTO> finByOpenid(String openid, Pageable pageable) {
        Page<OrderMaster> byBuyerOpenid = orderMasterDao.findByBuyerOpenid(openid, pageable);
        List<OrderDTO> orderDTOList = OrderMasterToOrdeDtoConverter.convert(byBuyerOpenid.getContent());
        Page<OrderDTO> pageList = new PageImpl<OrderDTO>(orderDTOList,pageable,byBuyerOpenid.getTotalElements());
        return pageList;
    }

    //    取消订单
    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        //查询订单状态
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("【取消订单】订单状态不正确！orderid{},orderstatus{}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //改变订单状态
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster upResult = orderMasterDao.save(orderMaster);
        if (upResult == null){
            log.error("【取消订单】更新订单状态失败！orderMaster{}",orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        //返还库存
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("【取消订单】订单中无商品！order{}",orderDTO);
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }
        List<CartDTO> cartDTOList= orderDTO.getOrderDetailList().stream().map(e ->
                new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());

        productInfoService.increaseStock(cartDTOList);

        //如果已付款 则退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS)){
            //TODO
        }

        return orderDTO;
    }

    //    完结订单
    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        //判断订单状态
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("[完结订单] 订单状态不是新订单！getOrderStatus = {}",orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //改变订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster upResult = orderMasterDao.save(orderMaster);
        if (upResult == null){
            log.error("【完结订单】更新订单状态失败！orderMaster{}",orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        return orderDTO;
    }

    //    支付订单
    @Override
    public OrderDTO paid(OrderDTO orderDTO) {
        //判断订单状态
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("[支付订单] 订单状态不是新订单！getOrderStatus = {}",orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //判断支付状态
        if (!orderDTO.getPayStatus().equals(ResultEnum.ORDER_PAY_STATUS_ERROR.getCode())){
            log.error("[支付订单] 订单状态不是待支付订单！PayStatus = {}",orderDTO.getPayStatus());
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }
        //更改支付状态
        orderDTO.setPayStatus(ResultEnum.ORDER_FINISH_SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster upResult = orderMasterDao.save(orderMaster);
        if (upResult == null){
            log.error("【支付订单】更新支付状态失败！orderMaster{}",orderMaster);
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        return orderDTO;
    }
}
